import argparse
import logging
import sys
import json
import requests

from proto_rpc_play.util.scaffold import Scaffold


class Main(Scaffold):
    def __init__(self, *argv):
        self.file = 'permissions.yaml'
        self.upload = False

        Scaffold.__init__(self, *argv)

    def configuration_options(self, arg_parser=argparse.ArgumentParser()):
        assert arg_parser

        arg_parser.add_argument('-f', '--file',
                                default=self.file,
                                help='The yaml file for upload or download.')
        arg_parser.add_argument('-u', '--upload',
                                default=self.upload,
                                action='store_true',
                                help='Activate flag to determine if upload operation is being '
                                     'attempted.')

    def run(self):
        self.log.info('Entering run state.')

        if self.upload:
            self.log.debug('Uploading file: %s', self.file)

            data = {}
            with open(self.file) as the_file:
                data['yaml'] = the_file.read()

            result = requests.post(
                url='http://localhost:8080/PermissionsService.post_permissions_yaml',
                headers={'content-type': 'application/json'},
                data=json.dumps(data))

            print 'result.status_code:', result.status_code
            if not result.ok:
                sys.stderr.write('HTTP RPC call failed with %s:%s'
                                 % (result.status_code, result.text))
                sys.stderr.flush()
                exit(-1)
        else:
            self.log.debug('Downloading to file: %s', self.file)

            result = requests.post(
                url='http://localhost:8080/PermissionsService.get_permissions_yaml',
                headers={'content-type': 'application/json'})

            # extract the yaml from the transmitted json object
            result_json = result.json()
            the_yaml = result_json['yaml']

            # write the yaml to file.
            with open(self.file, 'w') as the_file:
                the_file.write(the_yaml)

        logging.shutdown()


if __name__ == '__main__':
    argv = sys.argv
    main = Main(argv)
    main.run()
